package LeetCode;

public class LC_019_RemoveNthNodeFromEndofList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode listNode = removeNthFromEnd(head, 2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    private static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n < 1)
            return head;

        ListNode cur = head;
        while (cur != null) {
            n--;
            cur = cur.next;
        }


        if (n == 0) {
            head = head.next;
        }

        if (n < 0) {
            cur = head;
            while (++n != 0) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
        return head;
    }
}
